/*
 * (C) Copyright 2011, 2012
 *
 * Alexander Potashev, Emcraft Systems, aspotashev@emcraft.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */

#include <common.h>
#include <asm/errno.h>

#include "clock.h"


/*
 * Real Time Clock (RTC) register map
 */
struct kinetis_rtc_regs {
	u32 tsr;	/* RTC Time Seconds Register */
	u32 tpr;	/* RTC Time Prescaler Register */
	u32 tar;	/* RTC Time Alarm Register */
	u32 tcr;	/* RTC Time Compensation Register */
	u32 cr;		/* RTC Control Register */
	u32 sr;		/* RTC Status Register */
	u32 lr;		/* RTC Lock Register */
	u32 ier;	/* RTC Interrupt Enable Register */
	u32 ttsr;	/* RTC Tamper Time Seconds Register */
	u32 mer;	/* RTC Monotonic Enable Register */
	u32 mclr;	/* RTC Monotonic Counter Low Register */
	u32 mchr;	/* RTC Monotonic Counter High Register */
	u32 ter;	/* RTC Tamper Enable Register */
	u32 tdr;	/* RTC Tamper Detect Register */
	u32 ttr;	/* RTC Tamper Trim Register */
	u32 tir;	/* RTC Tamper Interrupt Register */
	u32 rsv0[496];
	u32 war;	/* RTC Write Access Register */
	u32 rar;	/* RTC Read Access Register */
};

/*
 * RTC registers base
 */
#define KINETIS_RTC_BASE		(KINETIS_AIPS0PERIPH_BASE + 0x0003D000)
#define KINETIS_RTC			((volatile struct kinetis_rtc_regs *) \
					KINETIS_RTC_BASE)

/*
 * Clock values
 */
static u32 clock_val[CLOCK_END];

/*
 * Enable OSCx module to control oscillator or external reference clock
 */
static void osc_enable(int osc)
{
	volatile struct kinetis_osc_regs *regs =
		(volatile struct kinetis_osc_regs *)kinetis_osc_base[osc];

	/*
	 * Enable clock on OSC1 module. OSC0 is always enabled.
	 */
	if (osc == 1)
		kinetis_periph_enable(KINETIS_CG_OSC1, 1);

	regs->cr = KINETIS_OSC_CR_EREFSTEN_MSK | KINETIS_OSC_CR_ERCLKEN_MSK;
}

/*
 * Set-up clocks
 */
static void clock_setup(void)
{
}

/*
 * Initialize the reference clocks.
 */
void clock_init(void)
{
	clock_setup();
}

/*
 * Return a clock value for the specified clock.
 *
 * @param clck          id of the clock
 * @returns             frequency of the clock
 */
unsigned long clock_get(enum clock clck)
{
	return clock_val[clck];
}

/*
 * Enable or disable the clock on a peripheral device (timers, UARTs, USB, etc)
 */
int kinetis_periph_enable(kinetis_clock_gate_t gate, int enable)
{
	rv = 0;
	return rv;
}
